import { Card, Descriptions, Divider, Table, Button, Tag } from 'antd';
import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Dispatch } from 'umi';
import { get } from 'lodash';
import { ORDER_STATUS, ORDER_ENUM } from '../../../common/constants';
import { OrderInfo } from './data.d';
import { orderDetail, orderReady, orderSend, orderFinish } from '../service';
import WaybillModel from './waybillModel';
import styles from './style.less';

interface BasicProps {
  loading: boolean;
  match: Object;
  dispatch: Dispatch<any>;
  profileAndbasic: any;
}
interface BasicState {
  loading: boolean;
  visible: boolean;
  data: OrderInfo;
}

class Basic extends Component<BasicProps, BasicState> {
  state: BasicState = {
    loading: false,
    visible: false,
    data: {
      id: '',
      order_id: '',
      status: '',
      transaction_id: '',
      total_fee: '',
      address: {
        name: '',
        user_id: '',
        address: '',
        mobile: '',
        address_detail: '',
      },
      order_goods: [],
    },
  };

  getDetail = async (id: string) => {
    this.setState({ loading: true });
    const { data, code } = await orderDetail(id);
    this.setState({ loading: false });
    if (code === 0) {
      this.setState({ data });
    }
  };

  async componentDidMount() {
    const { match } = this.props;
    const id = get(match, ['params', 'id'], '');
    if (id) {
      this.getDetail(id);
    }
  }

  // 配货
  readyGoods = async () => {
    const {
      data: { id },
    } = this.state;
    const { code } = await orderReady({ id });
    if (code === 0) {
      this.getDetail(id);
    }
  };

  // 发货完成
  sendGoods = async (data: any) => {
    const {
      data: { id },
    } = this.state;
    const { code } = await orderSend({ id, ...data });

    if (code === 0) {
      this.setState({ visible: false });
      this.getDetail(id);
    }
  };

  // 完成送货
  finishGoods = async () => {
    const {
      data: { id },
    } = this.state;
    const { code } = await orderFinish({ id });
    if (code === 0) {
      this.getDetail(id);
    }
  };

  render() {
    const { data, loading, visible } = this.state;
    const { address, order_goods: orderGoods } = data;
    let goodsData = [];
    if (orderGoods.length) {
      let number = 0;
      let price = 0;
      orderGoods.forEach((item) => {
        number += Number(item.number);
        price += Number(item.price);
      });
      goodsData = orderGoods.concat({
        id: '总计',
        number,
        price,
      });
    }
    const renderContent = (value: any, row: any, index: any) => {
      const obj: {
        children: any;
        props: { colSpan?: number };
      } = {
        children: value,
        props: {},
      };
      if (index === orderGoods.length) {
        obj.props.colSpan = 0;
      }
      return obj;
    };
    const goodsColumns = [
      {
        title: '商品ID',
        dataIndex: 'goods_id',
        key: 'goods_id',
        render: (text: React.ReactNode, row: any, index: number) => {
          if (index < orderGoods.length) {
            return <a href="">{text}</a>;
          }
          return {
            children: <span style={{ fontWeight: 600 }}>总计</span>,
            props: {
              colSpan: 3,
            },
          };
        },
      },
      {
        title: '商品名称',
        dataIndex: 'goods_name',
        key: 'goods_name',
        render: renderContent,
      },
      {
        title: '商品图片',
        dataIndex: 'main_pic',
        key: 'main_pic',
        render: (value: any, row: any, index: any) => {
          const obj: {
            children: any;
            props: { colSpan?: number };
          } = {
            children: <img alt="商品图片" src={value} style={{ width: 50, height: 50 }} />,
            props: {},
          };
          if (index === orderGoods.length) {
            obj.props.colSpan = 0;
          }
          return obj;
        },
      },
      {
        title: '数量',
        dataIndex: 'number',
        key: 'number',
        align: 'right' as 'left' | 'right' | 'center',
        render: (text: React.ReactNode, row: any, index: number) => {
          if (index < orderGoods.length) {
            return text;
          }
          return <span style={{ fontWeight: 600 }}>{text}</span>;
        },
      },
      {
        title: '金额',
        dataIndex: 'price',
        key: 'price',
        align: 'right' as 'left' | 'right' | 'center',
        render: (text: number, row: any, index: number) => {
          if (index < orderGoods.length) {
            return text / 100;
          }
          return <span style={{ fontWeight: 600 }}>{text / 100}</span>;
        },
      },
    ];

    const waybillProps = {
      onCancel: () => this.setState({ visible: false }),
      onOk: (it: any) => this.sendGoods(it),
    };

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Descriptions title="订单信息" style={{ marginBottom: 32 }}>
            <Descriptions.Item label="订单号">{data.order_id}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={ORDER_STATUS[data.status]?.color}>{ORDER_STATUS[data.status]?.txt}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="微信支付订单号">
              {data.transaction_id || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="支付金额">
              {data.total_fee ? data.total_fee / 100 : '-'}元
            </Descriptions.Item>
          </Descriptions>
          <Divider style={{ marginBottom: 32 }} />
          <Descriptions title="用户信息" style={{ marginBottom: 32 }}>
            <Descriptions.Item label="用户姓名">{address?.name || '-'}</Descriptions.Item>
            <Descriptions.Item label="联系电话">{address?.mobile || '-'}</Descriptions.Item>
            <Descriptions.Item label="常用快递">-</Descriptions.Item>
            <Descriptions.Item label="取货地址">{`${address?.address || '-'}/${
              address?.address_detail || '-'
            }`}</Descriptions.Item>
            <Descriptions.Item label="备注">无</Descriptions.Item>
          </Descriptions>
          <Divider style={{ marginBottom: 32 }} />
          <div className={styles.title}>商品信息</div>
          <Table
            style={{ marginBottom: 24 }}
            pagination={false}
            loading={loading}
            dataSource={goodsData}
            columns={goodsColumns}
            rowKey="id"
          />
          <Descriptions title="订单处理" style={{ marginBottom: 32 }}>
            <Descriptions.Item label="订单状态">
              <Tag color={ORDER_STATUS[data.status]?.color}>{ORDER_STATUS[data.status]?.txt}</Tag>
            </Descriptions.Item>
            {data.status === ORDER_ENUM.PAY && (
              <Descriptions.Item label="操作">
                <Button type="primary" onClick={this.readyGoods}>
                  确认配货
                </Button>
              </Descriptions.Item>
            )}
            {data.status === ORDER_ENUM.READY && (
              <Descriptions.Item label="操作">
                <Button type="primary" onClick={() => this.setState({ visible: true })}>
                  录入订单号
                </Button>
              </Descriptions.Item>
            )}
            {data.status === ORDER_ENUM.SENDING && (
              <Descriptions.Item label="操作">
                <Button type="primary" onClick={this.finishGoods}>
                  完成送货
                </Button>
              </Descriptions.Item>
            )}
          </Descriptions>
        </Card>
        {visible && <WaybillModel {...waybillProps} />}
      </PageHeaderWrapper>
    );
  }
}

export default Basic;
